package com.fruit.controller.app.user;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.joe.utils.common.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.fruit.common.CookieUtil;
import com.fruit.constants.RedisConstant;
import com.fruit.controller.base.BaseController;
import com.fruit.pojo.address.Address;
import com.fruit.pojo.common.Page;
import com.fruit.pojo.user.MyFruitTree;
import com.fruit.pojo.user.UserInfo;
import com.fruit.service.pic.PictureManager;
import com.fruit.service.redis.UserRedisUtil;
import com.fruit.service.rights.UserRightsManager;
import com.fruit.service.user.UserManager;
import com.fruit.util.CustomUtil;
import com.fruit.util.MessagesCode;
import com.fruit.util.ResultInfo;

/**
 * 用户controller
 *
 * @author Administrator
 * @version 2017.12.01 11:40
 */
@Controller
@RequestMapping(value = "/app/user/")
public class UserController extends BaseController {

    @Autowired
    private UserManager userService;

    @Autowired
    private PictureManager pictureService;

    @Autowired
    private UserRedisUtil userRedisService;

    @Autowired
    private UserRightsManager userRightsManager;

    @Value("${domain}")
    private String domain;

    @Value("${h5_domain}")
    private String h5Domain;

    @Value("${top_domain}")
    private String topDomain;

    @Value("${app.key}")
    private String key;

    /**
     * 通过用户id获取用户信息
     *
     * @param userId userId
     * @return Map<String, Object>
     */
    @RequestMapping(value = "userCenter", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public Map<String, Object> userCenter(String userId) {
        this.logBefore(logger, "用户信息");
        Map<String, Object> resMap = new HashMap<String, Object>();
        if (StringUtils.isEmpty(userId)) {
            resMap.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.MESS_OUT, "参数不全!"));
            return resMap;
        }
        try {
            UserInfo user = userService.getUser(Integer.parseInt(userId));
            if (user != null) {
                int rightNum = userRightsManager.getRightNum(user.getId());
                resMap.put("result", this.initResult(ResultInfo.SUCCESS, "SUCCESS", "查询成功!"));
                resMap.put("userInfo", user);
                resMap.put("rightNum", rightNum);
            } else {
                resMap.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.EXIST, "未找到用户!"));
            }
        } catch (Exception e) {
            this.logError(logger, e.getMessage());
            resMap.put("result", this.initResult(ResultInfo.ERROR, "expection", "系统繁忙!"));
        }
        return resMap;
    }

    /**
     * 收货地址信息
     *
     * @param userId userId
     * @return Map<String, Object>
     */
    @RequestMapping(value = "address/list", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public Map<String, Object> addressList(String userId) {
        this.logBefore(logger, "收货地址信息");
        Map<String, Object> resMap = new HashMap<String, Object>();
        if (StringUtils.isEmpty(userId)) {
            resMap.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.MESS_OUT, "参数不全!"));
            return resMap;
        }
        try {
            List<Address> address = userService.getAddressList(Integer.parseInt(userId));
            if (address.size() > 0) {
                resMap.put("result", this.initResult(ResultInfo.SUCCESS, "SUCCESS", "查询成功!"));
                resMap.put("address", address);
            } else {
                resMap.put("result", this.initResult(ResultInfo.SUCCESS, MessagesCode.MESS_ISnULL, "还未设置收货地址!"));
            }
        } catch (Exception e) {
            this.logError(logger, e.getMessage());
            resMap.put("result", this.initResult(ResultInfo.ERROR, "expection", "系统繁忙!"));
        }
        return resMap;
    }

    /**
     * 添加收货地址
     *
     * @param address address
     * @return Map<String, Object>
     */
    @RequestMapping(value = "address/save", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public Map<String, Object> saveAddress(Address address) {
        this.logBefore(logger, "添加收货地址");
        Map<String, Object> resMap = new HashMap<String, Object>();
        try {
            if (address == null) {
                resMap.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.MESS_OUT, "参数不全!"));
            } else {
                List<Address> addres = userService.getAddressList(address.getUserId());
                if (addres != null) {
                    for (Address addre : addres) {
                        if ("01".equals(address.getStatus())) {
                            if ("01".equals(addre.getStatus())) {
                                addre.setStatus("00");
                                userService.updateAddStatus(addre);
                            }
                        }
                    }
                }
                Address addre = userService.saveAddress(address);
                if (addre != null) {
                    resMap.put("result", this.initResult(ResultInfo.SUCCESS, "SUCCESS", "添加成功!"));
                    resMap.put("address", addre);
                }

            }
        } catch (Exception e) {
            this.logError(logger, e.getMessage());
            resMap.put("result", this.initResult(ResultInfo.ERROR, "expection", "系统繁忙!"));
        }
        return resMap;
    }

    /**
     * 修改收货地址
     *
     * @param address address
     * @return Map<String, Object>
     */
    @RequestMapping(value = "address/update", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public Map<String, Object> updateAddress(Address address) {
        this.logBefore(logger, "修改收货地址");
        Map<String, Object> resMap = new HashMap<String, Object>();
        try {
            if (address == null) {
                resMap.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.MESS_OUT, "参数不全!"));
            } else {
                if ("01".equals(address.getStatus())) {
                    List<Address> addres = userService.getAddressList(address.getUserId());
                    if (addres != null) {
                        for (Address addre : addres) {
                            if ("01".equals(address.getStatus())) {
                                if ("01".equals(addre.getStatus())) {
                                    addre.setStatus("00");
                                    userService.updateAddStatus(addre);
                                }
                            }
                        }
                    }
                }
                userService.updateAddress(address);
                Address addre = userService.getAddressById(address.getId());
                if (addre != null) {
                    resMap.put("result", this.initResult(ResultInfo.SUCCESS, "SUCCESS", "修改成功!"));
                    resMap.put("address", addre);
                }
            }
        } catch (Exception e) {
            this.logError(logger, e.getMessage());
            resMap.put("result", this.initResult(ResultInfo.ERROR, "expection", "系统繁忙!"));
        }
        return resMap;
    }

    /**
     * 收货地址信息
     *
     * @param addressId addressId
     * @return Map<String, Object>
     */
    @RequestMapping(value = "addressMsg", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public Map<String, Object> addressMsg(String addressId) {
        this.logBefore(logger, "收货地址信息");
        Map<String, Object> resMap = new HashMap<String, Object>();
        if (StringUtils.isEmpty(addressId)) {
            resMap.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.MESS_OUT, "参数不全!"));
            return resMap;
        }
        try {
            Address address = userService.getAddressById(Integer.parseInt(addressId));
            if (address != null) {
                resMap.put("result", this.initResult(ResultInfo.SUCCESS, "SUCCESS", "查询成功!"));
                resMap.put("address", address);
            } else {
                resMap.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.MESS_ISnULL, "未找到收货地址!"));
            }
        } catch (Exception e) {
            this.logError(logger, e.getMessage());
            resMap.put("result", this.initResult(ResultInfo.ERROR, "expection", "系统繁忙!"));
        }
        return resMap;
    }

    /**
     * 修改默认地址状态
     *
     * @param addressId addressId
     * @param userId    userId
     * @return Map<String, Object>
     */
    @RequestMapping(value = "address/updateStatus", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public Map<String, Object> updateStatus(String addressId, String userId) {
        this.logBefore(logger, "修改默认地址状态");
        Map<String, Object> resMap = new HashMap<String, Object>();
        if (StringUtils.isEmpty(addressId) || StringUtils.isEmpty(userId)) {
            resMap.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.MESS_OUT, "参数不全!"));
            return resMap;
        }
        try {
            List<Address> addres = userService.getAddressList(Integer.parseInt(userId));
            if (addres != null) {
                for (Address addre : addres) {
                    if ("01".equals(addre.getStatus())) {
                        addre.setStatus("00");
                        userService.updateAddStatus(addre);
                    }
                }
            }
            Address add = new Address();
            add.setStatus("01");
            add.setId(Integer.parseInt(addressId));
            userService.updateAddStatus(add);
            List<Address> addr = userService.getAddressList(Integer.parseInt(userId));
            if (addr != null) {
                resMap.put("result", this.initResult(ResultInfo.SUCCESS, "SUCCESS", "修改成功!"));
                resMap.put("address", addr);
            }
        } catch (Exception e) {
            this.logError(logger, e.getMessage());
            resMap.put("result", this.initResult(ResultInfo.ERROR, "expection", "系统繁忙!"));
        }
        return resMap;
    }

    /**
     * 删除收货地址
     *
     * @param addressId addressId
     * @return Map<String, Object>
     */
    @RequestMapping(value = "address/delete", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public Map<String, Object> deleteAddress(String addressId) {
        this.logBefore(logger, "删除收货地址");
        Map<String, Object> resMap = new HashMap<String, Object>();
        if (StringUtils.isEmpty(addressId)) {
            resMap.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.MESS_OUT, "参数不全!"));
            return resMap;
        }
        try {
            int num = userService.deleteAddress(Integer.parseInt(addressId));
            if (num == 0) {
                resMap.put("result", this.initResult(ResultInfo.ERROR, "ERROR", "删除失败!"));
            } else {
                resMap.put("result", this.initResult(ResultInfo.SUCCESS, "SUCCESS", "删除成功!"));
            }
        } catch (Exception e) {
            this.logError(logger, e.getMessage());
            resMap.put("result", this.initResult(ResultInfo.ERROR, "expection", "系统繁忙!"));
        }
        return resMap;
    }

    /**
     * app头像修改
     *
     * @param userId  userId
     * @param request request
     * @return Map<String, Object>
     */
    @RequestMapping(value = "headImage", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public Map<String, Object> groupImage(String userId, HttpServletRequest request) {
        this.logBefore(logger, "头像修改");
        Map<String, Object> resMap = new HashMap<String, Object>();
        if (StringUtils.isEmpty(userId)) {
            resMap.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.MESS_OUT, "参数不全!"));
            return resMap;
        }
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                request.getSession().getServletContext());
        if (multipartResolver.isMultipart(request)) {
            System.out.println("ss");
        }
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile file = multipartRequest.getFile("file");
        InputStream in = null;
        try {
            in = file.getInputStream();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        try {
            UserInfo user = userService.getUser(Integer.parseInt(userId));
            String path = "fruit/user/" + userId + "/head.png";
//            Map imagePath = pictureService.uploadPicture(path, in);
            Map imagePath = pictureService.uploadPicture(path, IOUtils.read(in, 1024));
            if (imagePath.size() == 0) {
                resMap.put("result", this.initResult(ResultInfo.ERROR, "error", "修改失败!"));
                return resMap;
            }
            int state = (int) imagePath.get("error");
            if (0 == state) {
                String imageAddress = (String) imagePath.get("url");
                user.setHeadImage(imageAddress + "?v" + CustomUtil.buildRandom(4));
                int num = userService.updateUserHeadImage(user);
                if (num == 0) {
                    resMap.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.ERROR, "修改失败!"));
                    return resMap;
                }
                UserInfo use = userService.getUser(Integer.parseInt(userId));
                if (use != null) {
                    resMap.put("result", this.initResult(ResultInfo.SUCCESS, MessagesCode.SUCCESS, "修改成功!"));
                    resMap.put("userInfo", use);
                }
            } else {
                resMap.put("result", this.initResult(ResultInfo.ERROR, "error", "修改失败!"));
                return resMap;
            }
        } catch (Exception e) {
            e.printStackTrace();
            this.logError(logger, e.getMessage());
            resMap.put("result", this.initResult(ResultInfo.ERROR, "expection", "系统繁忙!"));
        }
        return resMap;
    }

    /**
     * app用户信息修改 昵称 ,性别
     *
     * @param userId userId
     * @param user   user
     * @return Map<String, Object>
     */
    @RequestMapping(value = "userAlter", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public Map<String, Object> appUpdateUser(String userId, UserInfo user) {
        this.logBefore(logger, "用户修改");
        Map<String, Object> resMap = new HashMap<String, Object>();
        try {
            if (user == null || StringUtils.isEmpty(userId)) {
                resMap.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.MESS_OUT, "参数不全!"));
                return resMap;
            }
            UserInfo us = userService.getUser(Integer.parseInt(userId));
            if (us == null) {
                resMap.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.EXIST, "用户不存在!"));
                return resMap;
            }
            user.setVersion(us.getVersion());
            user.setId(Integer.parseInt(userId));
            int num = userService.updateUserMess(user);
            if (num == 0) {
                resMap.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.ERROR, "修改失败"));
                return resMap;
            } 
            UserInfo use = userService.getUser(Integer.parseInt(userId));
            if (use != null) {
                resMap.put("result", this.initResult(ResultInfo.SUCCESS, MessagesCode.SUCCESS, "修改成功"));
                resMap.put("userInfo", use);
            }
        } catch (Exception e) {
            e.printStackTrace();
            this.logError(logger, e.getMessage());
            if (user.getPetName() != null && user.getPetName() != "") {
            	resMap.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.ERROR, "修改失败"));
            	resMap.put("updateState","01");
            }else{
            	resMap.put("result", this.initResult(ResultInfo.ERROR, "expection", "网络繁忙!"));
            }
        }
        return resMap;
    }

    /**
     * 我的果树
     *
     * @param userId userId
     * @param page   page
     * @return Map<String, Object>
     */
    @RequestMapping(value = "farm", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public Map<String, Object> farm(String userId, Page page) {
        this.logBefore(logger, "我的果树");
        Map<String, Object> resMap = new HashMap<String, Object>();
        Map<String, Object> parame = new HashMap<String, Object>();
        try {
            if (StringUtils.isEmpty(userId)) {
                resMap.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.MESS_OUT, "参数不全!"));
                return resMap;
            }
            parame.put("start", (page.getPage() - 1) * page.getShowNum());
            parame.put("number", page.getShowNum());
            parame.put("userId", userId);
            List<MyFruitTree> myTree = userService.getMyFruitTreeList(parame);
            if (myTree == null || myTree.size() == 0) {
                resMap.put("result", this.initResult(ResultInfo.SUCCESS, MessagesCode.MESS_ISnULL, "您还未购买过商品!"));
            } else {
                resMap.put("result", this.initResult(ResultInfo.SUCCESS, MessagesCode.SUCCESS, "查询成功"));
                resMap.put("MyFruitTree", myTree);
            }
        } catch (Exception e) {
            e.printStackTrace();
            this.logError(logger, e.getMessage());
            resMap.put("result", this.initResult(ResultInfo.ERROR, "expection", "网络繁忙!"));
        }
        return resMap;
    }

    /**
     * 获取UserToken
     *
     * @param request  request
     * @param response response
     * @param loginId  loginId
     * @return Map<String, Object>
     */
    @RequestMapping(value = "getUserToken", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public Map<String, Object> getUserToken(HttpServletRequest request, HttpServletResponse response, int loginId) {
        this.logBefore(logger, "获取UserToken");
        Map<String, Object> resMap = new HashMap<String, Object>();
        try {
            boolean isCreateToken = true;
            String userToken = CookieUtil.getValue(request, "WAP_USER_TOOKEN");
            if (StringUtils.isNotEmpty(userToken)) {
                if (userRedisService.isExists(RedisConstant.WAP_USER_TOOKEN + userToken)) {
                    isCreateToken = false;
                    userRedisService.setUserTokenExpire(RedisConstant.WAP_USER_TOOKEN);
                }
            }
            if (isCreateToken) {
                UserInfo userInfo = userService.getUserInfoByLoginId(loginId);
                userToken = userRedisService.makeUserToken(userInfo.getId(), key);
                userRedisService.setUserToken(userInfo, userToken);
            }
            CookieUtil.setCookie(response, "WAP_USER_TOOKEN", userToken, 1, "/", topDomain);
            resMap.put("result", this.initResult(ResultInfo.SUCCESS, MessagesCode.SUCCESS, "成功"));
            resMap.put("WAP_USER_TOOKEN", userToken);
        } catch (Exception e) {
            e.printStackTrace();
            this.logError(logger, e.getMessage());
            resMap.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.SYSTEM, "系统繁忙!"));
        }
        this.logAfter(logger);
        return resMap;
    }

    /**
     * 修改密码
     *
     * @param request request
     * @return Map<String, Object>
     */
    @RequestMapping(value = "updateUserPwd", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public Map<String, Object> updateUserPwd(HttpServletRequest request) {
        this.logBefore(logger, "修改密码");
        Map<String, Object> resMap = new HashMap<String, Object>();
        String userId = request.getParameter("userId");
        String oldPwd = request.getParameter("oldPwd");
        String newPwd = request.getParameter("newPwd");
        try {
            if (StringUtils.isEmpty(userId) || StringUtils.isEmpty(oldPwd) || StringUtils.isEmpty(newPwd)) {
                resMap.put("result", this.initResult(ResultInfo.ERROR, "no-param", "参数不全!"));
                return resMap;
            }
            resMap = userService.updatePwd(userId, oldPwd, newPwd);
        } catch (Exception e) {
            e.printStackTrace();
            this.logError(logger, e.getMessage());
            resMap.put("result", this.initResult(ResultInfo.ERROR, "expection", "网络繁忙!"));
        }
        return resMap;
    }

    /**
     * 获取注册
     *
     * @param request request
     * @return Map<String, Object>
     */
    @RequestMapping(value = "getRegister", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public Map<String, Object> getRegister(HttpServletRequest request) {
        this.logBefore(logger, "获取注册");
        String userId = request.getParameter("userId");
        Map<String, Object> resMap = new HashMap<String, Object>();
        if (StringUtils.isEmpty(userId)) {
            resMap.put("result", this.initResult(ResultInfo.ERROR, "no-param", "参数不全!"));
            return resMap;
        }
        try {
            UserInfo ui = userService.getUser(Integer.parseInt(userId));
            if (ui != null) {
                String vipcode = ui.getCodePre() + userId + ui.getCodeSuf();
                String href = h5Domain + "/inviteLook?code=" + vipcode;
                resMap.put("href", href);
                resMap.put("result", this.initResult(ResultInfo.SUCCESS, "SUCCESS", "成功!"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            this.logError(logger, e.getMessage());
            resMap.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.SYSTEM, "系统繁忙!"));
        }
        this.logAfter(logger);
        return resMap;
    }
}
